//
//  XDXBaseTabBarViewController.m
//  tanhuo
//
//  Created by swartz007 on 2019/8/1.
//  Copyright © 2019 scout. All rights reserved.
//

#import "XDXBaseTabBarViewController.h"
#import "HomeViewController.h"
#import "TrackViewController.h"
#import "SafeViewController.h"
#import "XDXLocationManager.h"
#import <UserNotifications/UserNotifications.h>

@interface XDXBaseTabBarViewController ()<UITabBarDelegate,UNUserNotificationCenterDelegate>

@property (nonatomic, assign) NSInteger index;
@property (nonatomic, strong) UIView *configView;
@property (nonatomic, strong) UIView *locationBGView;
@property (nonatomic, strong) UIView *xdxTabBarView;                 // 自定义底部栏
@property (nonatomic, strong) NSArray<UIButton *> *xdxTabButtons;    // 自定义底部栏按钮
@property (nonatomic, assign) BOOL xdxCustomTabBarHidden;            // 是否强制隐藏自定义栏
@property (nonatomic, strong) UIImageView *locationImage;

@end

@implementation XDXBaseTabBarViewController

- (void)viewDidLoad {
    [super viewDidLoad];        
    
    UITabBarAppearance *appearance = [[UITabBarAppearance alloc] init];

    // 1. 去掉毛玻璃，改成不透明背景，接近 iOS14 之前效果
    [appearance configureWithOpaqueBackground];
    appearance.backgroundColor = RealWhiteColor;
    appearance.shadowColor = [UIColor colorWithWhite:0 alpha:0.1];

    // 2. 取消“气泡 / 胶囊”选中指示器（核心）
    // 给一个透明的选中指示图片，这样点击/选中就不会有那种玻璃气泡背景了
    appearance.selectionIndicatorImage = [UIImage new];

    // 3. 自己控制图标和文字的颜色（可选，但推荐配一下）
    UITabBarItemAppearance *item = appearance.stackedLayoutAppearance;
    UIColor *normalColor = [UIColor colorWithWhite:0.6 alpha:1.0];
    UIColor *selectedColor = NormalMainColor;

    item.normal.iconColor = normalColor;
    item.selected.iconColor = selectedColor;
    item.normal.titleTextAttributes   = @{NSForegroundColorAttributeName: normalColor};
    item.selected.titleTextAttributes = @{NSForegroundColorAttributeName: selectedColor};

    // 建议直接绑到当前 tabBar 实例上
    self.tabBar.standardAppearance = appearance;
    self.tabBar.scrollEdgeAppearance = appearance;
    
    NSString *nickName = [[NSUserDefaults standardUserDefaults] objectForKey:NickName];
    if (nickName && nickName.length>0) {
        [XDXShareInstance shareInstance].nickName = nickName;
    }
    NSString *userId = [[NSUserDefaults standardUserDefaults] objectForKey:UserId];
    if (userId && userId.integerValue>0) {
        [XDXShareInstance shareInstance].userId = userId;
    }
    NSString *avatar = [[NSUserDefaults standardUserDefaults] objectForKey:Avatar];
    if (avatar && avatar.length>0) {
        [XDXShareInstance shareInstance].avatar = avatar;
    }

    [[NSUserDefaults standardUserDefaults] setValue:@"1" forKey:FirstConfigInfo];
    [[NSUserDefaults standardUserDefaults] synchronize];
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:FirstLaunchApp] integerValue]>0) {
        // 请求所需权限并开始追踪
        [[XDXLocationManager shareInstance] loadData];
        [[XDXLocationManager shareInstance] initialize];
        [[XDXLocationManager shareInstance] getUserLocations];
        [[XDXLocationManager shareInstance].locationManager startUpdatingHeading];
        [[XDXLocationManager shareInstance].locationManager startUpdatingLocation];
        [[XDXLocationManager shareInstance].locationManager startMonitoringSignificantLocationChanges];
        [[XDXLocationManager shareInstance].locationManager startMonitoringVisits];
        
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        center.delegate = self;
        UNAuthorizationOptions type = UNAuthorizationOptionAlert|UNAuthorizationOptionCriticalAlert;
        [center requestAuthorizationWithOptions:type completionHandler:^(BOOL granted, NSError * _Nullable error) {
            if (granted) {
                
            }
        }];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
        
        [self setupUI];
    }else{
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(launchLocationNotify:) name:Noti_Launch_Location object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(launchNotificationNotify) name:Noti_Launch_Notification object:nil];
        
        _configView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-TABBARHEIGHT)];
        [self.view addSubview:_configView];
        
        UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(20, NAVHEIGHT+50, SCREEN_WIDTH-40, 36)];
        title.text = @"「家人足迹」 需要一些权限\n来保护你的安全";
        title.font = MEDIUM_FONT(24);
        title.textColor = RealBlackColor;
        title.textAlignment = NSTextAlignmentCenter;
        title.numberOfLines = 0;
        [title sizeToFit];
        [title setFrame:CGRectMake((SCREEN_WIDTH-title.width)/2, NAVHEIGHT+50, title.width, title.height)];
        [_configView addSubview:title];
        
        NSArray *array = @[@{@"image":@"launch_config_1",@"title":@"通知",@"subTitle":@"获取家庭重要消息"},@{@"image":@"launch_config_2",@"title":@"位置",@"subTitle":@"和家人共享位置"},@{@"image":@"launch_config_3",@"title":@"始终允许",@"subTitle":@"持续共享，守护安全"}];
        for (int i = 0; i<array.count; i ++) {
            UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(30, title.maxY+94+i*97, SCREEN_WIDTH-60, 46)];
            button.tag = 50+i;
            button.userInteractionEnabled = NO;
            [_configView addSubview:button];
            [[button rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
                NSURL * url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                [[UIApplication sharedApplication] openURL:url options:@{UIApplicationOpenURLOptionUniversalLinksOnly:@NO} completionHandler:nil];
            }];
            
            UIImageView *img = [[UIImageView alloc] initWithFrame:CGRectMake(0, (button.height-42)/2, 42, 42)];
            img.image = [UIImage imageNamed:array[i][@"image"]];
            [button addSubview:img];
            
            UILabel *title = [[UILabel alloc] initWithFrame:CGRectMake(img.maxX+16, 0, 70, 26)];
            title.textColor = RealBlackColor;
            title.font = REAL_MEDIUM_FONT(17);
            title.text = array[i][@"title"];
            [button addSubview:title];
            
            UILabel *subTitle = [[UILabel alloc] initWithFrame:CGRectMake(img.maxX+16, title.maxY+2, 130, 18)];
            subTitle.tag = 100+i;
            subTitle.textColor = GraryTooHeavyColor;
            subTitle.font = DEFAULT_FONT(14);
            subTitle.text = array[i][@"subTitle"];
            [button addSubview:subTitle];
            
            UIImageView *swImg = [[UIImageView alloc] initWithFrame:CGRectMake(button.width-46, (button.height-26)/2, 46, 26)];
            swImg.tag = 200+i;
            if (i==0) {
                
                [self checkNotificationAuthorizationWithImageView:swImg Button:button SubTitle:subTitle];
            }else if (i==1){
                [self checkLocationAuthorizationWithImageView:swImg Button:button SubTitle:subTitle Notify:nil];
            }else {
                [self checkLocationAuthorizationWithImageView:swImg Button:button SubTitle:subTitle Notify:nil];
            }
            [button addSubview:swImg];
        }
        
        UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(44, SCREEN_HEIGHT-138, SCREEN_WIDTH-88, 54)];
        button.backgroundColor = NormalMainColor;
        button.layer.masksToBounds = YES;
        [button.layer setCornerRadius:27];
        [button setTitle:@"开启权限" forState:UIControlStateNormal];
        [button.titleLabel setFont:REAL_MEDIUM_FONT(17)];
        [button setTitleColor:RealWhiteColor forState:UIControlStateNormal];
        [_configView addSubview:button];
        [[button rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
            if (button.titleLabel.text.length==4) {
                UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
                UNAuthorizationOptions type = UNAuthorizationOptionAlert|UNAuthorizationOptionCriticalAlert;
                [center requestAuthorizationWithOptions:type completionHandler:^(BOOL granted, NSError * _Nullable error) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        // 请求所需权限并开始追踪
                        self.locationBGView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
                        self.locationBGView.backgroundColor = [RealBlackColor colorWithAlphaComponent:0.4];
                        [self.view addSubview:self.locationBGView];
                        
//                        self.always = [[UIImageView alloc] initWithFrame:CGRectMake(-10, self.locationBGView.centerY+180, 58, 58)];
//                        self.always.image = [UIImage imageNamed:@"always_auth"];
//                        [self.locationBGView addSubview:self.always];
                        
                        self.locationImage = [[UIImageView alloc] initWithFrame:CGRectMake((SCREEN_WIDTH-229)/2, SCREEN_HEIGHT-139, 229, 85)];
                        self.locationImage.image = [UIImage imageNamed:@"when_auth"];
                        [self.locationBGView addSubview:self.locationImage];

                        
                        [self checkNotificationAuthorizationWithImageView:[self.view viewWithTag:200] Button:[self.view viewWithTag:50] SubTitle:[self.view viewWithTag:100]];
                        [[XDXLocationManager shareInstance] loadData];
                        [[XDXLocationManager shareInstance] initialize];
                        [[XDXLocationManager shareInstance] getUserLocations];
                        [[XDXLocationManager shareInstance].locationManager startUpdatingHeading];
                        [[XDXLocationManager shareInstance].locationManager startUpdatingLocation];
                        [[XDXLocationManager shareInstance].locationManager startMonitoringSignificantLocationChanges];
                        [[XDXLocationManager shareInstance].locationManager startMonitoringVisits];
                    });
                }];
                [[UIApplication sharedApplication] registerForRemoteNotifications];
                
                [button setTitle:@"进入家人足迹" forState:UIControlStateNormal];
            }else{
                [[NSUserDefaults standardUserDefaults] setValue:@"1" forKey:FirstLaunchApp];
                [[NSUserDefaults standardUserDefaults] synchronize];
                [self.configView removeFromSuperview];
                self.configView = nil;
                [self setupUI];
            }
        }];
    }
}

- (void)checkNotificationAuthorizationWithImageView:(UIImageView *)imageView
                                             Button:(UIButton *)button
                                           SubTitle:(UILabel *)subTitle
{
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    [center getNotificationSettingsWithCompletionHandler:^(UNNotificationSettings * _Nonnull settings) {
        switch (settings.authorizationStatus) {
            case UNAuthorizationStatusNotDetermined:
                {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        imageView.image = [UIImage imageNamed:@"config_un"];
                        button.userInteractionEnabled = NO;
                        subTitle.text = @"获取家庭重要消息";
                        subTitle.textColor = GraryTooHeavyColor;
                    });
                }
                break;
            case UNAuthorizationStatusDenied:
                {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        imageView.image = [UIImage imageNamed:@"config_off"];
                        button.userInteractionEnabled = YES;
                        subTitle.text = @"点击进行修复";
                        subTitle.textColor = RedColor;
                    });
                }
                break;
            case UNAuthorizationStatusAuthorized:
                {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        imageView.image = [UIImage imageNamed:@"config_on"];
                        button.userInteractionEnabled = NO;
                        subTitle.text = @"获取家庭重要消息";
                        subTitle.textColor = GraryTooHeavyColor;
                    });
                }
                break;
            case UNAuthorizationStatusProvisional:
                {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        imageView.image = [UIImage imageNamed:@"config_off"];
                        button.userInteractionEnabled = YES;
                        subTitle.text = @"点击进行修复";
                        subTitle.textColor = RedColor;
                    });
                }
                break;
            case UNAuthorizationStatusEphemeral:
                {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        imageView.image = [UIImage imageNamed:@"config_off"];
                        button.userInteractionEnabled = YES;
                        subTitle.text = @"点击进行修复";
                        subTitle.textColor = RedColor;
                    });
                }
                break;
        }
    }];
}

- (void)checkLocationAuthorizationWithImageView:(UIImageView *)imageView
                                         Button:(UIButton *)button
                                       SubTitle:(UILabel *)subTitle
                                         Notify:(NSNotification *)notify
{
    if ([[XDXLocationManager shareInstance].locationManager authorizationStatus]==kCLAuthorizationStatusNotDetermined) {
        imageView.image = [UIImage imageNamed:@"config_un"];
        button.userInteractionEnabled = NO;
        if (imageView.tag==201) {
            subTitle.text = @"和家人共享位置";
        }else if (imageView.tag==202){
            subTitle.text = @"持续共享，守护安全";
        }
        subTitle.textColor = GraryTooHeavyColor;
    }else{
        if (notify.userInfo) {
            [self.locationImage setFrame:CGRectMake((SCREEN_WIDTH-166)/2, SCREEN_HEIGHT-209, 166, 85)];
            self.locationImage.image = [UIImage imageNamed:@"always_auth"];
        }else{
            [self.locationBGView removeFromSuperview];
            self.locationBGView = nil;
        }

        if ([[XDXLocationManager shareInstance].locationManager authorizationStatus]==kCLAuthorizationStatusAuthorizedAlways) {
            imageView.image = [UIImage imageNamed:@"config_on"];
            button.userInteractionEnabled = NO;
            if (imageView.tag==201) {
                subTitle.text = @"和家人共享位置";
            }else if (imageView.tag==202){
                subTitle.text = @"持续共享，守护安全";
            }
            subTitle.textColor = GraryTooHeavyColor;
        }else if ([[XDXLocationManager shareInstance].locationManager authorizationStatus]==kCLAuthorizationStatusAuthorizedWhenInUse){
            if (imageView.tag==201) {
                imageView.image = [UIImage imageNamed:@"config_on"];
                button.userInteractionEnabled = NO;
                subTitle.text = @"和家人共享位置";
                subTitle.textColor = GraryTooHeavyColor;
            }else if (imageView.tag==202){
                if (!notify.userInfo) {
                    imageView.image = [UIImage imageNamed:@"config_off"];
                    button.userInteractionEnabled = YES;
                    subTitle.text = @"点击进行修复";
                    subTitle.textColor = RedColor;
                }
            }
        }else if ([[XDXLocationManager shareInstance].locationManager authorizationStatus]==kCLAuthorizationStatusDenied){
            imageView.image = [UIImage imageNamed:@"config_off"];
            button.userInteractionEnabled = YES;
            subTitle.text = @"点击进行修复";
            subTitle.textColor = RedColor;
        }else if ([[XDXLocationManager shareInstance].locationManager authorizationStatus]==kCLAuthorizationStatusRestricted){
            imageView.image = [UIImage imageNamed:@"config_off"];
            button.userInteractionEnabled = YES;
            subTitle.text = @"点击进行修复";
            subTitle.textColor = RedColor;
        }
    }
}

- (void)setupUI
{
    
    HomeViewController *home = [[HomeViewController alloc] init];
    UINavigationController *nav1 = [[UINavigationController alloc] initWithRootViewController:home];
    nav1.tabBarItem = [[UITabBarItem alloc] initWithTitle:@""
                                                    image:nil
                                            selectedImage:nil];

    SafeViewController *me = [[SafeViewController alloc] init];
    UINavigationController *nav2 = [[UINavigationController alloc] initWithRootViewController:me];
    nav2.tabBarItem = [[UITabBarItem alloc] initWithTitle:@""
                                                    image:nil
                                            selectedImage:nil];

    self.viewControllers = @[nav1, nav2];
    self.selectedIndex = 0;
    self.tabBar.tintColor = NormalMainColor;
    self.tabBar.backgroundColor = [UIColor clearColor];
    self.tabBar.alpha = 0;
    
    // 创建自定义底部栏，覆盖系统 TabBar，避免 iOS16 气泡挪动视觉
    [self xdx_setupCustomTabBar];
        
    NSMutableArray *anns = [NSMutableArray array];
    for (int i=17; i<=71; i++) {
        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@" splash_000%d",i]];
        [anns addObject:image];
    }
    UIImageView *launchAnn = [[UIImageView  alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    [launchAnn setAnimationImages:anns];
    launchAnn.animationRepeatCount = 1;
    [self.view addSubview:launchAnn];
    [launchAnn startAnimating];
    
}

- (void)setSelectedIndex:(NSUInteger)selectedIndex
{
    [super setSelectedIndex:selectedIndex];
    
    // 同步更新自定义底部栏按钮状态
    [self xdx_updateCustomTabBarSelection:selectedIndex];
}

- (void)xdx_setupCustomTabBar
{
    if (self.xdxTabBarView) {
        [self xdx_updateCustomTabBarSelection:self.selectedIndex];
        return;
    }
    
    UIView *tabBarView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, TABBARHEIGHT)];
    UIVisualEffectView *visualEffect = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleExtraLight]];
    visualEffect.frame = CGRectMake(0, 0, tabBarView.width, tabBarView.height);
    [tabBarView addSubview:visualEffect];
    
    // 顶部轻微阴影，模拟系统分割线
    tabBarView.layer.shadowColor = [[UIColor blackColor] colorWithAlphaComponent:0.05].CGColor;
    tabBarView.layer.shadowOpacity = 1.0;
    tabBarView.layer.shadowOffset = CGSizeMake(0, -0.5);
    tabBarView.layer.shadowRadius = 2.0;
    
    [self.view addSubview:tabBarView];
    [self.view bringSubviewToFront:tabBarView];
    self.xdxTabBarView = tabBarView;
    
    NSArray *titles = @[@"位置", @"我"];
    NSArray *normalImages = @[@"dingwei", @"anquan"];
    NSArray *selectedImages = @[@"dingwei-2", @"anquan-2"];
    
    NSMutableArray *buttons = [NSMutableArray array];
    CGFloat itemWidth = CGRectGetWidth(tabBarView.bounds) / titles.count;
    CGFloat barHeight = 54;
    
    for (NSInteger i = 0; i < titles.count; i++) {
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        btn.frame = CGRectMake(i * itemWidth, 0, itemWidth, barHeight);
        btn.tag = 1000 + i;
        
        [btn setImage:[UIImage imageNamed:normalImages[i]] forState:UIControlStateNormal];
        [btn setImage:[UIImage imageNamed:selectedImages[i]] forState:UIControlStateSelected];
        [btn setTitle:titles[i] forState:UIControlStateNormal];
        
        btn.titleLabel.font = DEFAULT_FONT(11);
        [btn setTitleColor:GraryHeavyLightColor forState:UIControlStateNormal];
        [btn setTitleColor:NormalMainColor forState:UIControlStateSelected];
        
        // 图片在上，文字在下
        CGFloat spacing = 3.0;
        CGSize imageSize = btn.imageView.intrinsicContentSize;
        CGSize titleSize = btn.titleLabel.intrinsicContentSize;
        CGFloat totalHeight = imageSize.height + spacing + titleSize.height;
        btn.imageEdgeInsets = UIEdgeInsetsMake(-(totalHeight - imageSize.height),
                                               0,
                                               0,
                                               -titleSize.width);
        btn.titleEdgeInsets = UIEdgeInsetsMake(0,
                                               -imageSize.width,
                                               -(totalHeight - titleSize.height),
                                               0);
        
        [btn addTarget:self action:@selector(xdx_tabButtonTapped:) forControlEvents:UIControlEventTouchUpInside];
        [tabBarView addSubview:btn];
        [buttons addObject:btn];
    }
    
    self.xdxTabButtons = buttons;
    [self xdx_updateCustomTabBarSelection:self.selectedIndex];
}

#pragma mark - 自定义 TabBar 点击 & 状态

- (void)xdx_tabButtonTapped:(UIButton *)sender
{
    NSInteger index = sender.tag - 1000;
    if (index < 0 || index >= self.viewControllers.count) {
        return;
    }
    UIImpactFeedbackGenerator *feedBackGenertor = [[UIImpactFeedbackGenerator alloc] initWithStyle:UIImpactFeedbackStyleLight];
    [feedBackGenertor impactOccurred];
    self.selectedIndex = index;
    [self xdx_updateCustomTabBarSelection:index];
}

- (void)xdx_updateCustomTabBarSelection:(NSUInteger)index
{
    if (self.xdxTabButtons.count == 0) return;
    
    [self.xdxTabButtons enumerateObjectsUsingBlock:^(UIButton * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        obj.selected = (idx == index);
    }];
}

#pragma mark - 对外：显示 / 隐藏自定义 TabBar

- (void)xdx_showCustomTabBar
{
    [self xdx_setCustomTabBarHidden:NO animated:YES];
}

- (void)xdx_hideCustomTabBar
{
    [self xdx_setCustomTabBarHidden:YES animated:YES];
}

- (void)xdx_setCustomTabBarHidden:(BOOL)hidden animated:(BOOL)animated
{
    self.xdxCustomTabBarHidden = hidden;
    
    if (!self.xdxTabBarView) return;
    
    if (!animated) {
        if (!hidden) {
            self.xdxTabBarView.y = SCREEN_HEIGHT-TABBARHEIGHT;
        } else {
            self.xdxTabBarView.y = SCREEN_HEIGHT;
        }
    }else{
        if (!hidden) {
            [UIView animateWithDuration:0.25 animations:^{
                self.xdxTabBarView.y = SCREEN_HEIGHT-TABBARHEIGHT;
            }];
        } else {
            [UIView animateWithDuration:0.25 animations:^{
                self.xdxTabBarView.y = SCREEN_HEIGHT;
            }];
        }
    }
}

- (void)launchLocationNotify:(NSNotification *)notify
{
    [self checkLocationAuthorizationWithImageView:[self.view viewWithTag:201] Button:[self.view viewWithTag:51] SubTitle:[self.view viewWithTag:101] Notify:notify];
    [self checkLocationAuthorizationWithImageView:[self.view viewWithTag:202] Button:[self.view viewWithTag:52] SubTitle:[self.view viewWithTag:102] Notify:notify];
}

- (void)launchNotificationNotify
{
    [self checkNotificationAuthorizationWithImageView:[self.view viewWithTag:200] Button:[self.view viewWithTag:50] SubTitle:[self.view viewWithTag:100]];
}

@end
